package com.thb.pay.core.interceptor;

import com.thb.pay.core.holder.LogContextHolder;
import com.thb.pay.core.utils.DateUtil;
import com.thb.pay.core.logs.utils.LogConstants;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Date;
import java.util.UUID;

/**
 * @author lucky
 * @ClassName SyncTrackInterceptor
 * @Description 异步链路 (mqtt 、 mq and so on.)前后拦截处理
 * @date 2019/3/1 9:08
 * @Version 1.0
 */
@Slf4j
@Getter
@Setter
public class SyncLogInterceptor {

    private String logReqId;

    private Thread currentThread;

    private Date currentDate;

    private String tempMethod;

    public SyncLogInterceptor() {
        logReqId = UUID.randomUUID().toString();
        currentDate = new Date();
        currentThread = Thread.currentThread();
        tempMethod = this.getClass().getName();
    }

    public SyncLogInterceptor(String logReqId, Thread currentThread, Date currentDate, String tempMethod) {
        this.logReqId = logReqId;
        this.currentThread = currentThread;
        this.currentDate = currentDate;
        this.tempMethod = tempMethod;
    }

    public void before() {
        String fileKey = String.format("%s/%s/%s/method%s/method%s.%s", DateUtil.getYear(currentDate), DateUtil.getMonth(currentDate), DateUtil.getDay(currentDate), tempMethod, tempMethod, logReqId);
        MDC.put(LogConstants.LOG_REQ_ID, logReqId);
        MDC.put(LogConstants.REQ_TIME_ID, String.valueOf(currentDate.getTime()));
        MDC.put(LogConstants.MAIN_THREAD_ID, String.valueOf(currentThread.getId()));
        MDC.put(LogConstants.MDC_ACTION, String.format("method%s", tempMethod));
        MDC.put(LogConstants.FILE_KEY, fileKey);
        LogContextHolder.setLogReqId(logReqId);
        LogContextHolder.setReqTimeId(currentDate.getTime());
        LogContextHolder.setFileKey(fileKey);
        LogContextHolder.setActionId(tempMethod);
    }

    public void after() {
        LogContextHolder.removeCurrentContextMap();
        MDC.clear();
    }
}
